//
//  BigTurnTableViewController.m
//  HongFuShop
//
//  Created by chirui on 2017/8/1.
//  Copyright © 2017年 Shui. All rights reserved.
//

#import "BigTurnTableViewController.h"
#import "TextView.h"

@interface BigTurnTableViewController ()<CAAnimationDelegate,UIAlertViewDelegate>
{
    UIView * alertBgView;
    NSDictionary * dataDic;
    
    NSInteger numbers;
    NSString * messageStr;
    NSString * cosePoint;
    TextView * pmView;

}
@property (nonatomic, strong) UIImageView *typeImageView;
@property (nonatomic, strong) UIButton    *startBtn;
@property (nonatomic, assign) BOOL        selected;


@property(nonatomic,strong) NSMutableArray *dataArray;

@end

@implementation BigTurnTableViewController


-(void)viewWillDisappear:(BOOL)animated {
    
     self.navigationController.navigationBarHidden =NO;
    
    [pmView stopAnimation];
    
}

-(void)viewWillAppear:(BOOL)animated {
    
    self.navigationController.navigationBarHidden = YES; //隐藏
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.dataArray = @[].mutableCopy;
    numbers = 0;
    
    self.view.backgroundColor =[UIColor whiteColor];
   
    [self getDataRequestFor];
    
}

-(void)creatScrollView{

    UIScrollView * scrollView =[[UIScrollView alloc]initWithFrame:CGRectMake(0, -20, WIDTH, HEIGHT+20)];
    [self.view addSubview:scrollView];
    //边界弹的效果，默认yes
    scrollView.bounces = NO;
    scrollView.backgroundColor = [UIColor whiteColor];
    scrollView.showsHorizontalScrollIndicator = NO;
    scrollView.showsVerticalScrollIndicator = NO;
    scrollView.pagingEnabled = NO;
    //    scrollView.delegate = self;
    scrollView.userInteractionEnabled = YES;
    
    scrollView.contentSize = CGSizeMake(WIDTH ,770);
    
    self.selected = NO;
    
    UIImageView * bgViewImage =[[UIImageView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, 770)];
    bgViewImage.userInteractionEnabled = YES;
    bgViewImage.image = ImageName(@"img_dial_bg");
    [scrollView addSubview:bgViewImage];
    
    //    UIImageView * titleImage =[[UIImageView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, 200)];
    //    titleImage.image = ImageName(@"img_dial_up_bg");
    //    [bgViewImage addSubview:titleImage];
    
    //
    UIImageView *bgImage = [[UIImageView alloc]initWithFrame:CGRectMake((WIDTH - 320)/2, 150, 320, 320 * 1.3)];
    bgImage.image = [UIImage imageNamed:@"icon_dial_flash"];
    bgViewImage.userInteractionEnabled = YES;
    bgImage.contentMode = UIViewContentModeScaleAspectFit;
    [bgViewImage addSubview:bgImage];
    //
    //
    self.typeImageView = [[UIImageView alloc] init];
    self.typeImageView.frame = CGRectMake(0, 0, 320 * 0.66, 320 * 0.66);
    self.typeImageView.layer.cornerRadius = 320 * 0.66 / 2;
    self.typeImageView.clipsToBounds = YES;
    CGPoint bgCenter = bgImage.center;
    bgCenter.y = bgCenter.y - 10;
    self.typeImageView.center = bgCenter;
    [self.typeImageView sd_setImageWithURL:ImageUrl(dataDic[@"pic"][0]) placeholderImage:ImageName(@"img_dial_disc")];
    [bgViewImage addSubview:self.typeImageView];
    //
    self.startBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.startBtn.frame = CGRectMake(0, 0, 320 * 0.3, 320 * 0.3);
    CGPoint btnCenter = bgImage.center;
    btnCenter.y -= 8;
    self.startBtn.center = btnCenter;
    
    [self.startBtn setImage:[UIImage imageNamed:@"icon_dial_pointer"] forState:UIControlStateNormal];
    [self.startBtn addTarget:self action:@selector(startBtn:) forControlEvents:UIControlEventTouchUpInside];
    [bgViewImage addSubview:self.startBtn];
    
    
    UIView * bgView = [[UIView alloc]initWithFrame:CGRectMake(20, CGRectGetMaxY(bgImage.frame)-30, WIDTH -40, 200)];
    bgView.backgroundColor = RGB(0xffac4b);
    bgView.layer.cornerRadius = 20.f;
    bgView.layer.masksToBounds = YES;
    [bgViewImage addSubview:bgView];
    
    UIImageView * heardTitle =[[UIImageView alloc]initWithFrame:CGRectMake((WIDTH - 265)/2, CGRectGetMaxY(bgImage.frame)-55, 265, 65)];
    heardTitle.image = ImageName(@"img_dial_record");
    [bgViewImage addSubview:heardTitle];
    
    
   pmView = [[TextView alloc]initWithFrame:CGRectMake(5, 40, WIDTH- 50, 160)];
    //    pmView.layer.borderWidth = 1.5;
    //    pmView.layer.borderColor = [UIColor colorWithRed:252 / 225.0 green:199 / 255.0 blue:191 / 255.0 alpha:1].CGColor;
    pmView.backgroundColor = [UIColor clearColor];
    //    pmView.layer.cornerRadius = 3;
    pmView.showNumber = true;//true 显示1排，，false显示2排
    pmView.clipsToBounds = YES;
    [bgView addSubview:pmView];
    if (_dataArray.count==0) {
        [pmView animationWithTexts:[NSMutableArray arrayWithObjects:@"", nil]];
    }else{
        [pmView animationWithTexts:_dataArray];
    }
    
    UIButton * backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    backBtn.frame = CGRectMake(10, 30, 30, 30);
    [backBtn setBackgroundImage:ImageName(@"icon_public_return") forState:UIControlStateNormal];
    backBtn.backgroundColor = [UIColor clearColor];
    [backBtn addTarget:self action:@selector(backButton) forControlEvents:UIControlEventTouchUpInside];
    [scrollView addSubview:backBtn];

}

-(void)backButton {

    [self.navigationController popViewControllerAnimated:YES];

}

-(void)startBtn: (UIButton *)sender {
    
    if (self.selected) {
        return;
    }
    
    if (numbers!=0) {
        
        [self starTurnRequestForType:@"1"];
        
    }else {
        
        UIAlertView * alert =[[UIAlertView alloc]initWithTitle:nil message:[NSString stringWithFormat:@"今天次数已用完，是否使用%@积分继续抽奖？",cosePoint] delegate:self cancelButtonTitle:@"确定" otherButtonTitles:@"取消", nil];
        [alert show];
 
    }
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {

    if (buttonIndex==0) {
        NSLog(@"确定");
        [self starTurnRequestForType:@"2"];
    }else {
    
        NSLog(@"取消");
    }
}

-(void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag {
    self.selected = NO;
    
    UIWindow *window = [[UIApplication sharedApplication].delegate window];
    
    alertBgView =[[UIView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT)];
    alertBgView.backgroundColor = ColorA(0, 0, 0, 0.5);
    
    
    UIImageView * image = [[UIImageView alloc]initWithFrame:CGRectMake((WIDTH - 265)/2, (HEIGHT-215)/2-40, 265, 215)];
    image.image = ImageName(@"img_window_bg");
    [alertBgView addSubview:image];
    
    
    UILabel * nameLabel =[[UILabel alloc]initWithFrame:CGRectMake(30, 130, 205, 30)];
    nameLabel.textAlignment = NSTextAlignmentCenter;
    nameLabel.font = [UIFont systemFontOfSize:16];
    nameLabel.textColor = RGB(0xf46048);
    nameLabel.text = messageStr;
    [image addSubview:nameLabel];
    
    
    UIButton * deledateBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    deledateBtn.frame = CGRectMake((WIDTH - 35)/2, CGRectGetMaxY(image.frame)+20, 35, 35);
    [deledateBtn setBackgroundImage:ImageName(@"icon_window_close") forState:UIControlStateNormal];
    [deledateBtn addTarget:self action:@selector(deledateBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [alertBgView addSubview:deledateBtn];
    
     [window addSubview:alertBgView];
}

-(void)deledateBtnClick {

    [alertBgView removeFromSuperview];

}

-(void)getDataRequestFor{
    
    NSDictionary * dic = @{@"user_id":USER_DEFAULTGet(@"user_id"),
                           @"token":USER_DEFAULTGet(@"token"),
                         };
    
    SHuiMBhubNoTimeLoding;
    [PostNetWorking postNetWorkingStr:RequestUrlStr(turn_luckInfo_api) andparameters:dic Success:^(id responseObject) {
        SHuiMBHidleYes;
        if (codeSucess) {
           dispatch_async(dispatch_get_global_queue(0, 0), ^{
               dataDic = responseObject[@"datas"];
               
               numbers = [dataDic[@"raff_number"] integerValue];
               cosePoint = dataDic[@"change_score"];
               
               if ([dataDic[@"list"] isKindOfClass:[NSArray class]]) {
                   if (self.dataArray.count>0) {
                       [self.dataArray removeAllObjects];
                   }
                   
                   for (NSDictionary * dic in dataDic[@"list"]) {
                       
                       NSString * str =  [NSString stringWithFormat:@"%@     %@     %@",dic[@"user_name"],dic[@"phone"],dic[@"content"]];
                       
                       [self.dataArray addObject:str];
                   }
               }
               dispatch_async(dispatch_get_main_queue(), ^{
                   
                   [self creatScrollView];
                
               });
           });
        }else {
            
            SHuiMBhudTextTimeStr(responseObject[@"mark"]);
        }
    } failed:^(NSError *error) {
        SHuiMBHidleYes;
        SHuiMBhudTextNetError;
    }];
}

//开始抽奖
-(void)starTurnRequestForType:(NSString *)type{
    
    NSDictionary * dic = @{@"user_id":USER_DEFAULTGet(@"user_id"),
                           @"token":USER_DEFAULTGet(@"token"),
                           @"type":type
                           };
    
    [PostNetWorking postNetWorkingStr:RequestUrlStr(turn_turnTable_api) andparameters:dic Success:^(id responseObject) {
        SHuiMBHidleYes;
        if (codeSucess) {
            
            
            
            self.selected = YES;
            
            self.typeImageView.transform = CGAffineTransformMakeRotation(0);
            
            NSInteger turnAngle;
            NSInteger randomNum = [responseObject[@"datas"][@"id"] integerValue];//控制概率
            NSInteger turnsNum = arc4random()%5+10;//控制圈数
            if (randomNum==1) {
                turnAngle = 0;
            } else if (randomNum==6) {
                
                turnAngle = 60;
                
            } else if (randomNum==5) {
                
                turnAngle = 120;
                
            } else if(randomNum==4){
                
                
                turnAngle = 180;
                
            }else if (randomNum==3){
                
                turnAngle = 240;
            }
            
            else{
                turnAngle = 300;
            }
            
            CGFloat perAngle = M_PI/180;
            
            CABasicAnimation* rotationAnimation;
            rotationAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
            rotationAnimation.toValue = [NSNumber numberWithFloat:turnAngle * perAngle + 360 * perAngle * turnsNum];
            rotationAnimation.duration = 3.0f;
            rotationAnimation.cumulative = YES;
            rotationAnimation.delegate = self;
            //由快变慢
            rotationAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut];
            rotationAnimation.fillMode=kCAFillModeForwards;
            rotationAnimation.removedOnCompletion = NO;
            [self.typeImageView.layer addAnimation:rotationAnimation forKey:@"rotationAnimation"];

            numbers = [responseObject[@"datas"][@"raff_number"] integerValue];
            messageStr = responseObject[@"datas"][@"message"];
            
        }else {
            
            SHuiMBhudTextTimeStr(responseObject[@"mark"]);
            
        }
        
    } failed:^(NSError *error) {
        SHuiMBHidleYes;
        SHuiMBhudTextNetError;
    }];
}

@end
